const app = getApp()
import { postSearchUser, postInviteMember } from '../../../../api/index'

Page({
  data: {
    keyword: '',
    list: []
  },
  async inviteMember () {
    try {
      let selections = this.data.list.filter(item => item.isSelected)
      if (!selections.length) {
        wx.showToast({ title: '请选择要邀请的成员！', icon: 'none' })
        return
      }
      wx.$pro.showLoading({ title: '邀请中...', mask: true })
      let userNameList = selections.map(item => { return item.userName })
      const { ResultSet } = await postInviteMember({ userNameList: userNameList })
      if (ResultSet.userData.failList) {
        wx.showToast({ title: '邀请失败，请稍后再试', icon: 'none' })
      } else {
        wx.showToast({ title: '邀请已发出', icon: 'none' })

      }
      wx.$pro.hideLoading()
      setTimeout(() => {
        wx.$nav.navigateBack()
      }, 1500)
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  selectMember ({ currentTarget: { dataset: { item, index } } }) {
    let key = `list[${index}].isSelected`
    this.setData({
      [key]: !item.isSelected
    })
  },
  search ({ detail }) {
    this.setData({ keyword: detail })
    this.getList()
  },
  async getList () {
    try {
      wx.$pro.showLoading({ title: '加载中...', mask: true})
      const { ResultSet } = await postSearchUser({ searchData: this.data.keyword })
      ResultSet.userData.data.forEach(item => {
        item.isSelected = false
      })
      this.setData({ list: ResultSet.userData.data })
      wx.$pro.hideLoading()
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad () {
    this.getList()
  }
})